package com.home.manager.service;


import com.home.manager.bean.User;
import com.home.manager.common.ManagerError;
import com.home.manager.exception.ApplicationError;
import com.home.manager.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {

    @Resource
    UserRepository userRepository;

    /**
     * 获取指定用户的权限
     *
     * @param userId
     * @return
     */
    public String getUserRole(Integer userId) {
        List<User> allUser = userRepository.getAllUser();
        if (CollectionUtils.isEmpty(allUser)) {
            throw new ApplicationError(ManagerError.NO_USER_EXISTS);
        }
        for (User user : allUser) {
            if (user.getUserId().equals(userId)) {
                return user.getRole();
            }
        }
        throw new ApplicationError(ManagerError.NO_USER);
    }

    /**
     * 获取有指定权限的用户名
     * @param resource
     * @return
     */
    public List<String> getByResource(String resource) {
        return null;
    }



    public void addUser(User user) {
        List<User> allUser = userRepository.getAllUser();
        if (allUser.stream().anyMatch(user1 -> user1.getUserId().equals(user.getUserId()))) {
            userRepository.updateUser(user);
            return;
        }
        userRepository.addUser(user);
    }

}
